﻿using System;
using Com.Enemy.EnemySystem.EnemyLifecycle;
using Pathfinding;
using UnityEngine;

namespace Script.Com.Enemy.EnemySystem.EnemyAI
{
    public class FollowPathAI : MonoBehaviour
    {
        
        private Path path;
        private Seeker seeker;

        private int currentWayPoint = 0;
        private bool reachedEndOfPath;
        
        
        private EnemyBody body;

        protected bool FaceRight
        {
            get;
            set;
        }
        
        public bool StartFinding 
        {
            get;
            set;
        }
        
        [SerializeField] protected float nextWayPointDistance = 1;

        
        private void Awake()
        {
            seeker = gameObject.AddComponent<Seeker>();
            body = GetComponent<EnemyBody>();
            InvokeRepeating(nameof(UpdatePath), 0f, .5f);

            FaceRight = transform.localScale.x < 0;
        }

        /// <summary>
        /// 以最短路径抵达target
        /// </summary>
        public void FollowPlayer() 
        {

            if (path == null)
                return;
            if (currentWayPoint >= path.vectorPath.Count) 
            {
                reachedEndOfPath = true;
                return;
            } else {
                reachedEndOfPath = false;
                StartFinding = false;
            }

            Vector2 direction = ((Vector2)path.vectorPath[currentWayPoint] - body.Rb.position).normalized;
            
            body.Rb.velocity = direction * (body.Data.FollowSpeed * Time.fixedDeltaTime);

            Flip(body.Target.position.x - transform.position.x);
            
            float distance = Vector2.Distance(body.Rb.position, path.vectorPath[currentWayPoint]);

            if (distance < nextWayPointDistance) 
            {
                currentWayPoint++;
            }
            
        }
        
        
        void UpdatePath() 
        {
            
            if(seeker.IsDone() && body.IsPlayerInArea)
                seeker.StartPath(body.Rb.position, body.Target.position, OnPathCompete);
        }
        
        void OnPathCompete(Path p) 
        {
            if (!p.error) {
                path = p;
                currentWayPoint = 0;
            }
        }
        
        void Flip()
        {
            Vector3 scale = transform.localScale;
            scale.x = -scale.x;
            transform.localScale = scale;

            FaceRight = !FaceRight;
        }

        public void Flip(float dir)
        {
            if (dir > 0 && !FaceRight) {
                Flip();
            } else if (dir < 0 && FaceRight) {
                Flip();
            }
        }
        
    }
}